import { Button, Form, Input, Table } from "antd";
import React from "react";
import { ModalForm } from "@ant-design/pro-components";
import { PlusOutlined } from "@ant-design/icons";

interface Props{
  value?: any;
  onChange?: (value?: any) =>void;
  rule: {
    columns: {key: string;title: string}[]
  }
}

export default function TableModal(props:Props){
  const {value,onChange, rule} =  props;

  const [form] = Form.useForm<any>();


  return <>
    <ModalForm
      form={form}
      title="填写数据"
      width={800}
      trigger={
        <Button>填写数据</Button>
      }
      onOpenChange={(visible)=>{
        if(visible){
          form.setFieldsValue({
            dataSource: value
          })
        }
      }}
      onFinish={(values)=>{
        onChange?.(values.dataSource);

        return Promise.resolve(true);
      }}
    >
      <Form.Item name="dataSource" valuePropName="dataSource">
        <Table
          pagination={false}
          rowKey="id"
          columns={rule.columns.map(item=>{
            return {
              ...item,
              render: (_,record,index)=>{
                return <Form.Item style={{marginBottom: 0}} name={['dataSource', index, item.key]}>
                  <Input  />
                </Form.Item>
              },
            }
          }).concat([
            {
              title: '操作',
              key: 'options',
              width: 60,
              render: (_,record)=>{
                return <Button type="link" onClick={()=>{
                  form.setFieldsValue({
                    dataSource: (form.getFieldsValue().dataSource ?? []).filter(item=>{
                      return item.id !== record.id;
                    })
                  })
                }}>删除</Button>
              }
            },
          ])}
          footer={()=>
            <Button block onClick={()=>{
              form.setFieldsValue({
                dataSource: [...(form.getFieldsValue().dataSource ?? []), {
                  id: `key-${Math.random().toString()}`,
                }]
              })
            }} >
              <PlusOutlined />
            </Button>
          }
        />
      </Form.Item>
    </ModalForm>
  </>


}
